<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2022-08-25 21:34:16
 * @LastEditors: CHINAKAIYUAN
 * @Description: 
 */

namespace App\Repositories;

use App\Models\OpenCard;
use App\Models\OpenCardGlue;
use App\Models\OpenCardGroundFabric;
use App\Models\OpenCardShellFabric;
use App\Models\Unit;
use DB;

class OpenCardRepository extends Repositories
    {
    public $relation_models = ["material", "creator", 'details', 'raws', 'process_route', 'salesman', 'linkman', 'customer', 'status'];
    public function boot(OpenCard $model)
        {
        $this->model = $model;
        }

    public function createDeailsStorage($open_card, $createShellFabric = true)
        {
        $open_quantity = 0;
        $open_card->details->filter(function ($v) use (&$open_quantity, $open_card, $createShellFabric)
            {
            //扣库逻辑
            $where   = [
                'grade'   => ['key' => 'grade', 'default' => 'A'],
                'batchno' => ['key' => 'batchno'],
                'craft'   => ['key' => 'craft', 'default' => '']
            ];
            $unit_id = $v->material->uunit_id;
            $rate    = UnitRepository::getRate($v->unit_id, $unit_id);
            if ($createShellFabric)
                OpenCardShellFabric::create([
                    'main_id'            => $v->id,
                    'batchno'            => $v->batchno,
                    'open_card_code'     => $open_card->code,
                    'customer_id'        => $v->customer_id,
                    'dyelot'             => $v->dyelot,
                    'material_id'        => $v->material_id,
                    'color_name'         => $v->color_name,
                    'quantity'           => $v->quantity * $rate,
                    'auxiliary_quantity' => $v->auxiliary_quantity,
                    'card_quantity'      => $v->quantity,
                    'card_unit_id'       => $v->unit_id,
                    'unit_id'            => $unit_id,
                ])->setWhere($where)->useStorage("生产领料");

            $open_quantity += $v->quantity * $rate;
            $v->save();
            });
        $this->createGroundFabricStorage($open_card, $open_quantity);
        $this->createGlue($open_card, $open_quantity);
        }
    public function nocreateDeailsStorage($open_card)
        {
        $open_card->details->filter(function ($v)
            {
            if ($v->shell_fabric?->status_id == 1) {
                fail("面布出库单[{$v->shell_fabric->open_card_code}]已出库！请先反审出库单！");
                }
            $v->shell_fabric?->nouseStorage()->delete();
            });
        $this->nocreateGroundFabricStorage($open_card);
        $this->nocreateGlue($open_card);
        }
    private function createGroundFabricStorage($model, $quantity)
        {
        $model->raws->filter(function ($v) use ($model, $quantity)
            {
            $data = [];
            if ($v->material) {
                $data['unit_id']  = $v->material->uunit_id;
                $data['quantity'] = $quantity * $v->rate / 100;
                //替换物料

                //替换物料(新物料ID
                if ($v->newmaterial_id > 0) {
                    $data['material_id'] = $v->newmaterial_id;
                    }
                else {
                    if (is_numeric($v->grade) && $v->grade > 0)
                        fail("已填降等备注必须填扣库膜！");
                    $data['material_id'] = $v->material_id;
                    }

                $data['main_id']        = $v->id;
                $data['open_card_code'] = $model->code;
                $data['customer_id']    = $model->customer_id;
                if ($v->material->category == null)
                    fail("{$v->material->name}分组未设置！");
                $data['customer_material'] = $v->material->category->name == '膜' ? 0 : $model->customer_material;
                OpenCardGroundFabric::create($data);
                }
            });
        }
    public function nocreateGroundFabricStorage($open_card)
        {
        $open_card->ground_fabric->filter(function ($v)
            {
            if ($v->status_id == 1) {
                fail("底布已出库！请选反审底布出库单！");
                }
            $v->delete();
            });
        }
    public function createGlue($open_card, $quantity)
        {
        $open_card->raws->filter(function ($v) use ($open_card, $quantity)
            {
            //64.47米/kg
            $meter_per_kg = $v->point_stick?->meter_per_kg;
            if (($meter_per_kg ?? 0) > 0) {
                $data                   = [];
                $data['unit_id']        = $v->material->uunit_id;
                $data['quantity']       = $quantity / $meter_per_kg;
                $data['material_id']    = $v->glue_id;
                $data['customer_id']    = $open_card->customer_id;
                $data['main_id']        = $v->id;
                $data['open_card_code'] = $open_card->code;
                }
            else {
                fail("点棍每公斤可贴米数不正确！");
                }
            OpenCardGlue::create($data);
            });
        }
    public function nocreateGlue($open_card)
        {
        $open_card->glue->filter(function ($v)
            {
            if ($v->status_id == 1)
                fail("胶水出库单[{$v->open_card_code}]已审核！请先反审胶水出库单");
            $v->delete();
            });
        }
    //构成数据    
    public function createBom($data)
        {
        $ddata = ['status_id' => 0, 'name' => $data->bom['name'], 'craft_category_id' => $data->craft_category_id, 'details' => $data->raws];
        return ProBomRepository::validate($ddata)->autosave($ddata);
        }
    public function editgetDataRequest()
        {

        $request   = request();
        $oldbom_id = $this->whereId($request->main['id'])->value("bom_id");

        if (is_numeric($oldbom_id) && $oldbom_id > 0) {
            fail("BOM已存在！无法更新！");
            }

        $bom_m = null;
        if (isEmpty($request->bom['name'])) {
            fail("工艺BOM必选！");
            }

        if (isEmpty($request->bom_id)) {
            $bom_m = $this->createBom($request);
            }
        else {
            if (ProBomRepository::whereId($request->bom_id)->value("name") != $request->bom['name']) {
                $bom_m = $this->createBom($request);
                }
            }
        if ($bom_m) {
            $request->raws = $bom_m->details->map(function ($v)
                {
                unset($v['id']);
                return $v;
                })->toArray();

            $request->bom_id = $bom_m->id;
            }

        $data = [
            'id'      => $request->main['id'],
            'bom_id'  => $request->bom_id,
            'details' => array_map(function ($v) use ($request)
                {

                $v['scheduling'] = array_map(function ($vv) use ($request)
                    {
                    return [
                        'material_id'      => $vv['material_id'],
                        'point_stick_id'   => $vv['point_stick_id'],
                        'glue_id'          => $vv['glue_id'],
                        'customer_id'      => $request->customer_id,
                        'quantity'         => $request->quantity,
                        'process_name'     => $vv['process_name'],
                        'machine_id'       => $request->machine_id ?? 0,
                        'process_route_id' => $request->process_route_id,
                    ];
                    }, $request->raws);
                return $v;
                }, $request->details),
            'raws'    => $request->raws,
        ];
        return $data;
        }
    public function getDataRequest()
        {
        $request = request();
        if (isEmpty($request->process_route_id)) {
            fail('工艺线路必须选！');
            }
        $bom_m = null;
        if (isNotEmpty($request->bom['name'])) {


            if (isEmpty($request->bom_id)) {
                $bom_m = $this->createBom($request);
                }
            else {
                // if (ProBomRepository::whereId($request->bom_id)->value("name") != $request->bom['name']) {
                //     // 查询相同名称的直接赋值
                //     $bom_m = $this->createBom($request);
                //     }
                if (ProBomRepository::whereId($request->bom_id)->value("name") != $request->bom['name']) {
                    // 检查是否已存在同名的 BOM
                    $sameBom = ProBomRepository::where('name', $request->bom['name'])->first();
                    if ($sameBom) {
                        // 如果已存在同名 BOM，直接使用
                        $bom_m = $sameBom;
                    } else {
                        // 不存在同名 BOM，创建新的
                        $bom_m = $this->createBom($request);
                    }
                }
                }
                
            if ($bom_m != null) {
                $request->raws   = $bom_m->details->map(function ($v)
                    {
                    unset($v['id']);
                    return $v;
                    })->toArray();
                $request->bom_id = $bom_m->id;
                }
            }
        else {
            $request->bom_id = 0;
            $request->raws   = [];
            }
        $quantity                   = $auxiliary_quantity = 0;
        $data                       = [
            'id'                      => $request->id ?? 0,
            'material_id'             => $request->material_id,
            'is_sample'               => $request->is_sample,
            'salesman_id'             => $request->salesman_id,
            'customer_id'             => $request->customer_id,
            'linkman_id'              => $request->linkman_id,
            'process_route_id'        => $request->process_route_id,
            'customer_material'       => $request->customer_material,
            'film_category_id'        => $request->film_category_id,
            'craft_category_id'       => $request->craft_category_id,
            'bom_id'                  => $request->bom_id,
            'machine_id'              => $request->machine_id,
            'water_pressure'          => $request->water_pressure,
            'washed_index_id'         => $request->washed_index_id,
            'strip_index_id'          => $request->strip_index_id,
            'soak'                    => $request->soak,
            'process_requirements'    => $request->process_requirements,
            'inspection_requirements' => $request->inspection_requirements,
            'packaging_requirements'  => $request->packaging_requirements,
            'joint_gap'               => $request->joint_gap,
            'glue_gap'                => $request->glue_gap,
            'oil_temperature'         => $request->oil_temperature,
            'glue_temperature'        => $request->glue_temperature,
            'needInspect'             => $request->needInspect ?? 0,
            'needEndInspect'          => $request->needEndInspect,
            'details'                 => array_map(function ($v) use (&$auxiliary_quantity, &$quantity, $request)
                {
                unset(
                    $v['status_id'],
                    $v['open_quantity'],
                    $v['location_id'],
                    $v['lack_quantity'],
                    $v['salesman_id'],
                    $v['employee_id'],
                    $v['fect_quantity'],
                    $v['fect_auxiliary_quantity'],
                    $v['first_check_status_id'],
                    $v['reel'],
                    $v['storage_quantity'],
                    $v['material_quantity'],
                    $v['pro_quantity']
                );
                $v['main_id']       = 0;
                $quantity += $v['quantity'];
                $auxiliary_quantity += $v['auxiliary_quantity'];
                $v['scheduling'] = array_map(function ($vv) use ($request)
                    {
                    return [
                        'material_id'      => $vv['material_id'],
                        'point_stick_id'   => $vv['point_stick_id'],
                        'glue_id'          => $vv['glue_id'],
                        'customer_id'      => $request->customer_id,
                        'quantity'         => $request->quantity,
                        'process_name'     => $vv['process_name'],
                        'machine_id'       => $request->machine_id ?? 0,
                        'process_route_id' => $request->process_route_id,
                    ];
                    }, $request->raws);
                return $v;
                }, $request->details),
            'raws'                    => $request->raws,
        ];
        $data['quantity']           = $quantity;
        $data['auxiliary_quantity'] = $auxiliary_quantity;
        return $data;
        }
    }
